package edu.njust.httpmanager.aop;

import edu.njust.httpmanager.annotation.AuthCheck;
import edu.njust.httpmanager.common.Result;
import edu.njust.httpmanager.common.UserContext;
import edu.njust.httpmanager.constance.UserAuth;
import edu.njust.httpmanager.entity.ProgramMember;
import edu.njust.httpmanager.service.IProgramMemberService;
import edu.njust.httpmanager.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthCheckInterceptor {

    @Resource
    IProgramMemberService memberService;

    @Around(value = "edu.njust.httpmanager.aop.PointCut.programId(authCheck)", argNames = "joinPoint,authCheck")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {

        // 获取项目ID，用户ID
        Object[] args = joinPoint.getArgs();

        // 从第一个参数获取项目id
        Long programId = (Long) args[0];
        // 从最后一个参数获取用户id
        Long userId = UserContext.getUser().getId();

        // 获取要求的角色信息
        String mustRole = authCheck.value();

        // 从数据库获取用户的实际权限
        ProgramMember auth = memberService.getAuth(userId, programId);

        // 查看用户是否有权限
        if (!mustRole.equals(auth.getUserRole()) && !UserAuth.ADMIN.equals(auth.getUserRole())) {
            return Result.error("无权限，需要权限：" + mustRole);
        }
        return joinPoint.proceed();

    }
}
